<template>
    <div class="lyric-main" style="max-height: 65vh;" ref="lyriclist">
        <div class="lyrics" style="transform: translateY(0px);">
            <!-- :class="{'active':true}" -->
            <p :title="lrc.content" class="lyric-item" v-for="lrc, index in props.lyric" :data-time="lrc.time"
                :class="{ 'active': index == lrcindex }" :data-index="index">{{ lrc.content }}</p>
            <p v-if="props.lyric.length == 0" data-index="1" class="lyric-item active">暂无歌词
            </p>
            <br><br>
        </div>
    </div>
</template>

<script setup>
import { usePlayE } from '@/stores/playlist'
import { ref, onMounted, nextTick, watch } from 'vue'
import { useRoute } from 'vue-router';


const route = useRoute()
const playE = usePlayE()
const props = defineProps({
    lyric: {
        type: Array,
        required: true
    }
})
const lrcindex = ref(0)//当前歌词索引
const lyriclist = ref(null)

const scrollLyric = () => {
    try {
        //遍历lyriclist下的所有p标签，找到有data-index为lrcindex的p标签
        const active = lyriclist.value.querySelector(`.lyrics p[data-index="${lrcindex.value}"]`)
        //获取当前索引元素相对于父元素的高度
        const height = active.offsetTop || 0
        //获取父元素的高度
        const parentHeight = lyriclist.value.clientHeight
        //获取当前索引元素的高度
        const activeHeight = active.clientHeight
        //获取当前索引元素距离父元素顶部的距离
        const top = height - parentHeight / 2 + activeHeight / 2


        // num:歌词滚动的距离
        nextTick(() => {
            lyriclist.value.scrollTo({ top: top, behavior: 'smooth' });
        })
    }
    catch (err) {
        // console.log(err)
    }
}

//监听playE的变化
watch(() => playE.playE, (newVal, oldVal) => {

    //newVal是当前播放的时间
    const list = document.querySelectorAll('.lyrics p')
    for (let i = 0; i < list.length; ++i) {
        const current = list[i]
        const next = list[i + 1]
        if (newVal >= current.dataset.time) {
            //如果存在下一句歌词，且当前播放时间小于下一句歌词的时间
            if (next && newVal < next.dataset.time) {
                lrcindex.value = i
                scrollLyric()
                break
            }
            //如果是最后一句歌词
            if (i === list.length - 1) {
                lrcindex.value = i
                scrollLyric()
                break
            }
        }
    }
}, { deep: true })
</script>

<style lang="less" scoped>
.lyric-main {
    min-height: 120px;
    height: 100%;
    overflow-y: auto;
    transition: all 1.5s;

    &::-webkit-scrollbar {
        width: 0 !important;
    }

    &::-webkit-scrollbar {
        width: 0 !important;
        height: 0;
    }

    .lyrics {
        .lyric-item {
            &:hover {
                cursor: pointer;
            }
        }

        p {
            margin: 0;
            line-height: 30px;
            font-size: 14px;
            font-weight: 300;
            color: #141414;
        }

        .active {
            color: #409eff;
        }
    }

}
</style>